using UnityEngine;
using System.Collections;

/**
 * Movement behavior for a bullet prefab. Relies on bullet's Transform.rotation
 */
public class BulletMovement : MonoBehaviour {
	public GameObject deadBullet;
	
	/**
	 * Enemy movement speed.
	 **/
	public const float xDelta = -20;
	public const float maxDistanceX = 500;
	public const float yFloor = -9;
	
	/**
	 * Direction Vector3.
	 **/
	public Vector3 direction;
	
	public Vector3 source;
	
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
		float diff = (xDelta * Time.deltaTime);
		Vector3 normal = direction.normalized;
		
		this.transform.Translate( new Vector3( normal.x * diff, normal.y* diff, 0 ) );
		
		// kill if off screen?
		float distX = transform.position.x - source.x;
		if (distX < 0)
			distX *= -1;
		if (distX > maxDistanceX) {
			Destroy( this.gameObject );
		}
		
		// too low?
		if (this.transform.position.y < yFloor) {
			Destroy( this.gameObject );
		}
	}
	
	/**
	 * Handles collisions
	 **/
	void OnTriggerEnter ( Collider other ) {
		// did we hit the player?
		if (other.gameObject.CompareTag( "EnemyOne" ))
			return;
		
		if (other.gameObject.CompareTag( "Player" )) {
			// kill player
			GenerateObjects.getPlayer().GetComponent<CharacterManager>().respawn();
		}
			
		GameObject madeThis = (GameObject) Instantiate( deadBullet, this.transform.position, Quaternion.identity );
		madeThis.GetComponent<DestroyAfter>().killAtTime = (Time.timeSinceLevelLoad + 2f);
		Destroy( this.gameObject );
	}
}
